package com.j1ay.forum.service.impl;

import com.j1ay.forum.dao.mapper.PermissionMapper;
import com.j1ay.forum.model.pojo.po.Permission;
import com.j1ay.forum.model.pojo.po.User;
import com.j1ay.forum.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author J1ay
 * @Date 2021/12/18 11:02
 * @Description
 */

@Service
@Slf4j
public class AuthService {

    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Autowired
    private UserService userService;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        //权限认证，请求路径
        String requestURI = request.getRequestURI();
        log.info("request url:{}", requestURI);
        //true代表放行 false 代表拦截
        Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal)){
            //未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        User user = userService.findUserById(username);
        log.info("user:{}", user);
        if (user == null){
            return false;
        }
        if (user.getRoleId() == 3){
            log.info("权限通过");
            //认为是超级管理员
            return true;
        }
        List<Permission> permissions = permissionMapper.findPermissionsByRoleId(user.getRoleId());
        log.info("permissions:{}", permissions);
        requestURI = StringUtils.split(requestURI,'?')[0];
        for (Permission permission : permissions) {
            if (requestURI.equals(permission.getPath())){
                log.info("权限通过");
                return true;
            }
        }
        log.info("权限不通过");
        return false;
    }
}
